A closure is a function that remembers its outer variables and can access them. All functions in JavaScript are closures.
The closure has three scope chains:
- it has access to its own scope — variables defined between its curly brackets
- it has access to the outer function’s variables
- it has access to the global variables
Example of closure
function outer() {
let i = 1;
return function inner() {
const a = 10;
const result = a * i;
i = i + 1;
return result;
};
}
const inner = outer(); //get instance of inner function
console.log(inner()); // 10
console.log(inner()); // 20
console.log(inner()); // 30
Use:
Mostly, closures are used for encapsulation in javascript. You can declare private variables using closures. These variables will be hidden for other functions/methods. Consider another example of closure as:
function counter() {
var c = 0;
return {
inc: function () {
++c;
},
dec: function () {
--c;
},
get: function () {
return c;
},
reset: function () {
c = 0;
},
};
}
const myCounter = counter();
console.log(myCounter.inc());
console.log(myCounter.get()); //1
console.log(myCounter.dec());
console.log(myCounter.reset());
Inner variables and functions of counter function are hidden from other functions. Using closure you can encapsulate your private methods. Consider another example:
function calculate() {
const rate = 5;
return {
intrest: function (principal, time) {
return (principal * rate * time) / 100;
},
totalAccruedAmount: function (principal, time) {
return principal + (principal * rate * time) / 100;
},
};
}
const calculator = calculate();
console.log(calculator.intrest(1000, 5));
console.log(calculator.totalAccruedAmount(1000, 5));
In this example interest rate is private and only closure functions can access interest rate. It is hidden from the outer scope and cant be accessed by other scopes.
You can use closures to hide implementation details and declare private variables.
